/*
   -----------------------------------------------------------------------------
   This source file is part of OGRE
   (Object-oriented Graphics Rendering Engine)
   For the latest info, see http://www.ogre3d.org/

   Copyright (c) 2000-2011 Torus Knot Software Ltd

   Permission is hereby granted, free of charge, to any person obtaining a copy
   of this software and associated documentation files (the "Software"), to deal
   in the Software without restriction, including without limitation the rights
   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   copies of the Software, and to permit persons to whom the Software is
   furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   THE SOFTWARE.
   -----------------------------------------------------------------------------
   */

#include <assert.h>
#include <math.h>
#include "Math.h"
#include "asm_math.h"
#include "Vec2f.h"
#include "Vec3f.h"
#include "Vec4f.h"
#include "Matrix3.h"
#include "Matrix4.h"



const float Math::POS_INFINITY = std::numeric_limits<float>::infinity();
const float Math::NEG_INFINITY = -std::numeric_limits<float>::infinity();
const float Math::PI = float( 4.0 * atan( 1.0 ) );
const float Math::TWO_PI = float( 2.0 * PI );
const float Math::HALF_PI = float( 0.5 * PI );
const float Math::fDeg2Rad = PI / float(180.0);
const float Math::fRad2Deg = float(180.0) / PI;
const float Math::LOG2 = log(float(2.0));

int Math::mTrigTableSize;
Math::AngleUnit Math::msAngleUnit;

float  Math::mTrigTableFactor;
float *Math::mSinTable = NULL;
float *Math::mTanTable = NULL;

//-----------------------------------------------------------------------
Math::Math( unsigned int trigTableSize )
{
	msAngleUnit = AU_DEGREE;

	mTrigTableSize = trigTableSize;
	mTrigTableFactor = mTrigTableSize / Math::TWO_PI;

	mSinTable = new float[mTrigTableSize];
	mTanTable = new float[mTrigTableSize];

	buildTrigTables();
}

//-----------------------------------------------------------------------
Math::~Math()
{
	delete[] mSinTable;
	delete[] mTanTable;
}

//-----------------------------------------------------------------------
void Math::buildTrigTables(void)
{
	// Build trig lookup tables
	// Could get away with building only PI sized Sin table but simpler this 
	// way. Who cares, it'll ony use an extra 8k of memory anyway and I like 
	// simplicity.
	float angle;
	for (int i = 0; i < mTrigTableSize; ++i)
	{
		angle = Math::TWO_PI * i / mTrigTableSize;
		mSinTable[i] = sin(angle);
		mTanTable[i] = tan(angle);
	}
}
//-----------------------------------------------------------------------	
float Math::SinTable (float fValue)
{
	// Convert range to index values, wrap if required
	int idx;
	if (fValue >= 0)
	{
		idx = int(fValue * mTrigTableFactor) % mTrigTableSize;
	}
	else
	{
		idx = mTrigTableSize - (int(-fValue * mTrigTableFactor) % mTrigTableSize) - 1;
	}

	return mSinTable[idx];
}
//-----------------------------------------------------------------------
float Math::TanTable (float fValue)
{
	// Convert range to index values, wrap if required
	int idx = int(fValue *= mTrigTableFactor) % mTrigTableSize;
	return mTanTable[idx];
}
//-----------------------------------------------------------------------
int Math::ISign (int iValue)
{
	return ( iValue > 0 ? +1 : ( iValue < 0 ? -1 : 0 ) );
}
//-----------------------------------------------------------------------
Radian Math::ACos (float fValue)
{
	if ( -1.0 < fValue )
	{
		if ( fValue < 1.0 )
			return Radian(acos(fValue));
		else
			return Radian(0.0);
	}
	else
	{
		return Radian(PI);
	}
}
//-----------------------------------------------------------------------
Radian Math::ASin (float fValue)
{
	if ( -1.0 < fValue )
	{
		if ( fValue < 1.0 )
			return Radian(asin(fValue));
		else
			return Radian(HALF_PI);
	}
	else
	{
		return Radian(-HALF_PI);
	}
}
//-----------------------------------------------------------------------
float Math::Sign (float fValue)
{
	if ( fValue > 0.0 )
		return 1.0;

	if ( fValue < 0.0 )
		return -1.0;

	return 0.0;
}
//-----------------------------------------------------------------------
float Math::InvSqrt(float fValue)
{
	return float(asm_rsq(fValue));
}
//-----------------------------------------------------------------------
float Math::UnitRandom ()
{
	return asm_rand() / asm_rand_max();
}

//-----------------------------------------------------------------------
float Math::RangeRandom (float fLow, float fHigh)
{
	return (fHigh-fLow)*UnitRandom() + fLow;
}

//-----------------------------------------------------------------------
float Math::SymmetricRandom ()
{
	return 2.0f * UnitRandom() - 1.0f;
}

//-----------------------------------------------------------------------
void Math::setAngleUnit(Math::AngleUnit unit)
{
	msAngleUnit = unit;
}
//-----------------------------------------------------------------------
Math::AngleUnit Math::getAngleUnit(void)
{
	return msAngleUnit;
}
//-----------------------------------------------------------------------
float Math::AngleUnitsToRadians(float angleunits)
{
	if (msAngleUnit == AU_DEGREE)
		return angleunits * fDeg2Rad;
	else
		return angleunits;
}

//-----------------------------------------------------------------------
float Math::RadiansToAngleUnits(float radians)
{
	if (msAngleUnit == AU_DEGREE)
		return radians * fRad2Deg;
	else
		return radians;
}

//-----------------------------------------------------------------------
float Math::AngleUnitsToDegrees(float angleunits)
{
	if (msAngleUnit == AU_RADIAN)
		return angleunits * fRad2Deg;
	else
		return angleunits;
}

//-----------------------------------------------------------------------
float Math::DegreesToAngleUnits(float degrees)
{
	if (msAngleUnit == AU_RADIAN)
		return degrees * fDeg2Rad;
	else
		return degrees;
}

//-----------------------------------------------------------------------
bool Math::pointInTri2D(const Vector2f& p, const Vector2f& a, 
		const Vector2f& b, const Vector2f& c)
{
	// Winding must be consistent from all edges for point to be inside
	Vector2f v1, v2;
	float dot[3];
	bool zeroDot[3];

	v1 = b - a;
	v2 = p - a;

	// Note we don't care about normalisation here since sign is all we need
	// It means we don't have to worry about magnitude of cross products either
	dot[0] = v1.crossProduct(v2);
	zeroDot[0] = Math::floatEqual(dot[0], 0.0f, 1e-3);


	v1 = c - b;
	v2 = p - b;

	dot[1] = v1.crossProduct(v2);
	zeroDot[1] = Math::floatEqual(dot[1], 0.0f, 1e-3);

	// Compare signs (ignore colinear / coincident points)
	if(!zeroDot[0] && !zeroDot[1] 
			&& Math::Sign(dot[0]) != Math::Sign(dot[1]))
	{
		return false;
	}

	v1 = a - c;
	v2 = p - c;

	dot[2] = v1.crossProduct(v2);
	zeroDot[2] = Math::floatEqual(dot[2], 0.0f, 1e-3);
	// Compare signs (ignore colinear / coincident points)
	if((!zeroDot[0] && !zeroDot[2] 
				&& Math::Sign(dot[0]) != Math::Sign(dot[2])) ||
			(!zeroDot[1] && !zeroDot[2] 
			 && Math::Sign(dot[1]) != Math::Sign(dot[2])))
	{
		return false;
	}


	return true;
}
//-----------------------------------------------------------------------
bool Math::pointInTri3D(const Vector3f& p, const Vector3f& a, 
		const Vector3f& b, const Vector3f& c, const Vector3f& normal)
{
	// Winding must be consistent from all edges for point to be inside
	Vector3f v1, v2;
	float dot[3];
	bool zeroDot[3];

	v1 = b - a;
	v2 = p - a;

	// Note we don't care about normalisation here since sign is all we need
	// It means we don't have to worry about magnitude of cross products either
	dot[0] = v1.crossProduct(v2).dotProduct(normal);
	zeroDot[0] = Math::floatEqual(dot[0], 0.0f, 1e-3);


	v1 = c - b;
	v2 = p - b;

	dot[1] = v1.crossProduct(v2).dotProduct(normal);
	zeroDot[1] = Math::floatEqual(dot[1], 0.0f, 1e-3);

	// Compare signs (ignore colinear / coincident points)
	if(!zeroDot[0] && !zeroDot[1] 
			&& Math::Sign(dot[0]) != Math::Sign(dot[1]))
	{
		return false;
	}

	v1 = a - c;
	v2 = p - c;

	dot[2] = v1.crossProduct(v2).dotProduct(normal);
	zeroDot[2] = Math::floatEqual(dot[2], 0.0f, 1e-3);
	// Compare signs (ignore colinear / coincident points)
	if((!zeroDot[0] && !zeroDot[2] 
				&& Math::Sign(dot[0]) != Math::Sign(dot[2])) ||
			(!zeroDot[1] && !zeroDot[2] 
			 && Math::Sign(dot[1]) != Math::Sign(dot[2])))
	{
		return false;
	}


	return true;
}
//-----------------------------------------------------------------------
bool Math::floatEqual( float a, float b, float tolerance )
{
	if (fabs(b-a) <= tolerance)
		return true;
	else
		return false;
}
//-----------------------------------------------------------------------
Vector3f Math::calculateTangentSpaceVector(
		const Vector3f& position1, const Vector3f& position2, const Vector3f& position3,
		float u1, float v1, float u2, float v2, float u3, float v3)
{
	//side0 is the vector along one side of the triangle of vertices passed in, 
	//and side1 is the vector along another side. Taking the cross product of these returns the normal.
	Vector3f side0 = position1 - position2;
	Vector3f side1 = position3 - position1;
	//Calculate face normal
	Vector3f normal = side1.crossProduct(side0);
	normal.normalise();
	//Now we use a formula to calculate the tangent. 
	float deltaV0 = v1 - v2;
	float deltaV1 = v3 - v1;
	Vector3f tangent = deltaV1 * side0 - deltaV0 * side1;
	tangent.normalise();
	//Calculate binormal
	float deltaU0 = u1 - u2;
	float deltaU1 = u3 - u1;
	Vector3f binormal = deltaU1 * side0 - deltaU0 * side1;
	binormal.normalise();
	//Now, we take the cross product of the tangents to get a vector which 
	//should point in the same direction as our normal calculated above. 
	//If it points in the opposite direction (the dot product between the normals is less than zero), 
	//then we need to reverse the s and t tangents. 
	//This is because the triangle has been mirrored when going from tangent space to object space.
	//reverse tangents if necessary
	Vector3f tangentCross = tangent.crossProduct(binormal);
	if (tangentCross.dotProduct(normal) < 0.0f)
	{
		tangent = -tangent;
		binormal = -binormal;
	}

	return tangent;

}
//-----------------------------------------------------------------------
Vector4f Math::calculateFaceNormal(const Vector3f& v1, const Vector3f& v2, const Vector3f& v3)
{
	Vector3f normal = calculateBasicFaceNormal(v1, v2, v3);
	// Now set up the w (distance of tri from origin
	return Vector4f(normal.x, normal.y, normal.z, -(normal.dotProduct(v1)));
}
//-----------------------------------------------------------------------
Vector3f Math::calculateBasicFaceNormal(const Vector3f& v1, const Vector3f& v2, const Vector3f& v3)
{
	Vector3f normal = (v2 - v1).crossProduct(v3 - v1);
	normal.normalise();
	return normal;
}
//-----------------------------------------------------------------------
Vector4f Math::calculateFaceNormalWithoutNormalize(const Vector3f& v1, const Vector3f& v2, const Vector3f& v3)
{
	Vector3f normal = calculateBasicFaceNormalWithoutNormalize(v1, v2, v3);
	// Now set up the w (distance of tri from origin)
	return Vector4f(normal.x, normal.y, normal.z, -(normal.dotProduct(v1)));
}
//-----------------------------------------------------------------------
Vector3f Math::calculateBasicFaceNormalWithoutNormalize(const Vector3f& v1, const Vector3f& v2, const Vector3f& v3)
{
	Vector3f normal = (v2 - v1).crossProduct(v3 - v1);
	return normal;
}
//-----------------------------------------------------------------------
float Math::gaussianDistribution(float x, float offset, float scale)
{
	float nom = Math::Exp(
			-Math::Sqr(x - offset) / (2 * Math::Sqr(scale)));
	float denom = scale * Math::Sqrt(2 * Math::PI);

	return nom / denom;

}
//---------------------------------------------------------------------
Matrix4 Math::makeViewMatrix(const Vector3f& position, const Quaternion& orientation, 
		const Matrix4* reflectMatrix)
{
	Matrix4 viewMatrix;

	// View matrix is:
	//
	//  [ Lx  Uy  Dz  Tx  ]
	//  [ Lx  Uy  Dz  Ty  ]
	//  [ Lx  Uy  Dz  Tz  ]
	//  [ 0   0   0   1   ]
	//
	// Where T = -(Transposed(Rot) * Pos)

	// This is most efficiently done using 3x3 Matrices
	Matrix3 rot;
	orientation.ToRotationMatrix(rot);

	// Make the translation relative to new axes
	Matrix3 rotT = rot.Transpose();
	Vector3f trans = -rotT * position;

	// Make final matrix
	viewMatrix = Matrix4::IDENTITY;
	viewMatrix = rotT; // fills upper 3x3
	viewMatrix[0][3] = trans.x;
	viewMatrix[1][3] = trans.y;
	viewMatrix[2][3] = trans.z;

	// Deal with reflections
	if (reflectMatrix)
	{
		viewMatrix = viewMatrix * (*reflectMatrix);
	}

	return viewMatrix;

}
//---------------------------------------------------------------------

